package woa.tree.binary;

/**
 * 二叉树的最近公共祖先
 * 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
 * 对于有根树 T 的两个节点 p、q，最近公共祖先表示为一个节点 x，满足 x 是 p、q 的祖先且 x 的深度尽可能大（一个节点也可以是它自己的祖先）
 *
 * 输入：root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
 * 输出：3
 * 解释：节点 5 和节点 1 的最近公共祖先是节点 3 。
 *
 * @author wangpeng
 * @date 2021/12/4
 */
public class LowestCommonAncestor {

    static TreeNode target;

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        dfs(root, p, q);
        return target;
    }

    public static boolean dfs(TreeNode cur, TreeNode p, TreeNode q) {
        if (cur == null) {
            return false;
        }
        boolean left = dfs(cur.left, p, q);
        boolean right = dfs(cur.right, p, q);
        if ((left && right) || ((left || right) && (cur == p || cur == q))) {
            target = cur;
        }
        return left || right || (cur == p || cur == q);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode left = new TreeNode(5);
        TreeNode right = new TreeNode(1);
        root.left = left;
        root.right = right;
        System.out.println(lowestCommonAncestor(root, left, right).val);
    }
}
